//
//  TTPageScrollView.swift
//  ScrollViewReView
//
//  Created by Pro on 2018/4/10.
//  Copyright © 2018年 Pro. All rights reserved.
//

import UIKit

class TTPageScrollView: UIView {

    public typealias PageViewBuilder = (_ containerView:UIView,_ index:Int,_ frame:CGRect)->Void
    
    fileprivate var widthContraint:NSLayoutConstraint? = nil
    
    fileprivate class InternalScrollView:UIScrollView {
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            return true
        }
    }
    
   open lazy var scrollView:UIScrollView! = {
        var v = InternalScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.clipsToBounds = false
        v.isPagingEnabled = true
        v.showsVerticalScrollIndicator = false
        v.showsHorizontalScrollIndicator = false
        return v
    }()
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.setup()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }
    fileprivate func setup(){
        self.addSubview(self.scrollView)
        self.addConstraint(NSLayoutConstraint(item: self.scrollView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: self.scrollView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: self.scrollView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0))
        self.widthContraint = NSLayoutConstraint(item: self.scrollView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)
        self.addConstraint(self.widthContraint!)
        }
    
    func config(viewSpace space:Float = 5.0, edgesForExtended:Float, pageNumber:Int, pageViewBuilder:PageViewBuilder){
        guard pageNumber > 0 else {return}
        let internalScrollViewWIdthConstance = (space + edgesForExtended)
        self.widthContraint?.constant = CGFloat(-internalScrollViewWIdthConstance)
        self.layoutIfNeeded()
        
        let scrollviewWidth = self.bounds.size.width - CGFloat(internalScrollViewWIdthConstance)
        self.scrollView.contentSize = CGSize(width: scrollviewWidth * CGFloat(pageNumber), height: self.bounds.size.height)
        
        for index in 0 ..< pageNumber {
            let frame = CGRect(x: CGFloat(index) * scrollviewWidth, y: 0.0, width: scrollviewWidth, height: self.bounds.size.height)
            let frame2 = frame.insetBy(dx: CGFloat(space), dy: 0 )
            pageViewBuilder(self.scrollView,index,frame2)
        }
    }
    
    func scrollToPage(_ page:Int) {
        self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.size.width, y: 0.0)
    }

}
